<template>
  <div class="new-scoring-page">
    <!-- 隐藏的全屏拖放区域 -->
    <div
      v-show="isDragOver"
      class="fullscreen-drag-overlay"
      @drop.prevent="handleGlobalDrop"
      @dragover.prevent
      @dragenter.prevent="isDragOver = true"
      @dragleave.prevent="isDragOver = false"
    >
      <div class="drag-overlay-content">
        <el-icon class="drag-overlay-icon"><UploadFilled /></el-icon>
        <h3>松手即可上传</h3>
        <p>将内镜图像文件拖放到此处</p>
      </div>
    </div>

    <div class="scoring-grid-container">
      <!-- 顶部标题区域 -->
      <header class="page-header slide-in">
        <h1 class="page-title">开始评分</h1>
        <div class="header-actions">
          <!-- 模型状态指示器 -->
          <div class="model-status-badge" :class="modelStatus.status" fade-in>
            <div class="status-dot" :class="modelStatus.status"></div>
            <span class="status-text">
              {{ modelStatus.status === 'checking' ? '检查AI模型中...' :
                 modelStatus.status === 'available' ? 'AI模型运行正常' :
                 'AI模型未启动' }}
            </span>
          </div>
        </div>
      </header>

      <!-- 主要内容区域：CSS Grid布局 -->
      <main class="scoring-main-grid">
        <!-- 左侧：上传表单区域 -->
        <section class="upload-section">
          <el-card class="upload-card glass-effect scale-in" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon class="header-icon"><Upload /></el-icon>
                <span>上传内镜图像和临床信息</span>
                <div class="ai-model-indicator" v-if="modelStatus.status === 'available'">
                  <el-icon class="ai-icon"><DataAnalysis /></el-icon>
                  <span>AI已就绪</span>
                </div>
              </div>
            </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="formRules"
            label-width="120px"
            class="scoring-form"
            @submit.prevent="handleSubmit"
          >
            <!-- 图像上传 -->
            <el-form-item label="内镜图像" prop="image" required>
              <el-upload
                ref="uploadRef"
                class="medical-upload"
                drag
                :auto-upload="false"
                :show-file-list="false"
                accept="image/jpeg,image/png,image/dcm,image/bmp"
                :limit="1"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
              >
                <div v-if="!form.image" class="upload-container">
                  <el-icon class="upload-icon"><UploadFilled /></el-icon>
                  <div class="upload-text">点击或拖拽文件到此处上传</div>
                  <div class="upload-hint">支持 JPG、PNG、DICOM、BMP 格式，文件大小不超过 10MB</div>
                </div>
                <div v-else class="uploaded-file">
                  <el-image
                    :src="imagePreview"
                    :preview-src-list="[imagePreview]"
                    class="preview-image"
                    fit="cover"
                  />
                  <div class="file-info">
                    <div class="file-name">{{ form.image.name }}</div>
                    <el-button
                      type="danger"
                      text
                      size="small"
                      @click.stop="handleFileRemove"
                    >
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
              </el-upload>
            </el-form-item>

            <!-- 患者编号 -->
            <el-form-item label="患者编号" prop="patient_code">
              <el-input
                v-model="form.patient_code"
                placeholder="请输入患者匿名编号（可留空自动生成）"
                clearable
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <!-- 临床文本信息 -->
            <el-form-item label="临床信息" prop="clinical_text">
              <el-input
                v-model="form.clinical_text"
                type="textarea"
                :rows="4"
                placeholder="请输入患者的临床症状、病史等临床信息（可选）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item class="submit-section">
              <el-button
                type="primary"
                size="large"
                :loading="submitting"
                @click="handleSubmit"
                class="submit-button aperture-hover-lift aperture-press-down"
                @mouseenter="onButtonHover"
                @mouseleave="onButtonLeave"
              >
                <el-icon><Document /></el-icon>
                {{ submitting ? 'AI分析中...' : '提交评分任务' }}
              </el-button>
            </el-form-item>
          </el-form>

          <!-- AI分析进度显示 -->
          <div v-if="submitting || analysisProgress.show" class="analysis-progress-card">
            <el-card class="progress-card glass-effect" shadow="never">
              <template #header>
                <div class="progress-header">
                  <el-icon class="progress-icon"><Loading /></el-icon>
                  <span>AI分析进度</span>
                </div>
              </template>
              
              <div class="progress-content">
                <!-- 进度条 -->
                <div class="progress-bar-container">
                  <el-progress 
                    :percentage="analysisProgress.percentage" 
                    :status="analysisProgress.status"
                    :stroke-width="8"
                    :show-text="true"
                  >
                    <template #default="{ percentage }">
                      <span class="progress-text">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>

                <!-- 当前步骤 -->
                <div class="current-step">
                  <el-icon><Clock /></el-icon>
                  <span>{{ analysisProgress.currentStep }}</span>
                </div>

                <!-- 详细步骤 -->
                <div class="step-details">
                  <div 
                    v-for="(step, index) in analysisProgress.steps" 
                    :key="index"
                    class="step-item"
                    :class="{
                      'completed': step.completed,
                      'current': step.current,
                      'pending': !step.completed && !step.current
                    }"
                  >
                    <el-icon class="step-icon">
                      <Check v-if="step.completed" />
                      <Loading v-else-if="step.current" />
                      <Clock v-else />
                    </el-icon>
                    <span class="step-text">{{ step.text }}</span>
                    <span class="step-time">{{ step.time }}</span>
                  </div>
                </div>

                <!-- 预计剩余时间 -->
                <div class="estimated-time" v-if="analysisProgress.estimatedTime">
                  <el-icon><Timer /></el-icon>
                  <span>预计剩余时间: {{ analysisProgress.estimatedTime }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-card>
        </section>

        <!-- 右侧：评分结果区域 -->
        <section class="result-section">
          <el-card class="result-card glass-effect scale-in" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon class="header-icon"><DataAnalysis /></el-icon>
                <span>AI分析结果</span>
                <div class="result-status" v-if="currentTask">
                  <el-icon v-if="currentTask.task_info.status === 1 || currentTask.task_info.status === 2" class="loading-icon">
                    <Loading />
                  </el-icon>
                </div>
              </div>
            </template>

          <!-- 未提交状态 -->
          <div v-if="!currentTask" class="empty-result">
            <el-empty description="请先提交左侧信息">
              <template #image>
                <el-icon class="empty-icon"><Document /></el-icon>
              </template>
            </el-empty>
          </div>

          <!-- 分析中状态 - 使用骨架屏 -->
          <div v-else-if="currentTask.task_info.status === 1 || currentTask.task_info.status === 2" class="analyzing-result">
            <ScoringSkeleton />
          </div>

          <!-- 分析完成状态 -->
          <div v-else-if="currentTask.ai_result" class="completed-result">
            <el-descriptions
              :column="1"
              border
              class="result-descriptions"
            >
              <el-descriptions-item label="AI评分值">
                <el-tag type="primary" size="large" class="score-tag">
                  <span class="score-display">{{ currentTask.ai_result.score }}</span> 分
                </el-tag>
              </el-descriptions-item>

              <el-descriptions-item label="严重程度">
                <div class="severity-container">
                  <div class="severity-pill" :class="getSeverityClass(currentTask.ai_result.severity)">
                    <div class="severity-icon">
                      <component :is="getSeverityIcon(currentTask.ai_result.severity)" />
                    </div>
                    <div class="severity-content">
                      <div class="severity-title">{{ currentTask.ai_result.severity_name }}</div>
                      <div class="severity-subtitle">{{ getSeverityDescription(currentTask.ai_result.severity) }}</div>
                    </div>
                    <div class="severity-score"><span class="score-display">{{ currentTask.ai_result.score }}</span>分</div>
                  </div>
                  <div class="severity-indicators">
                    <div class="indicator"
                         v-for="(level, index) in severityLevels"
                         :key="index"
                         :class="{ active: level.value <= currentTask.ai_result.severity }">
                    </div>
                  </div>
                </div>
              </el-descriptions-item>

              <el-descriptions-item label="置信度分析">
                <div class="confidence-visualization">
                  <!-- 置信度环形图 -->
                  <div ref="chartRef" class="confidence-chart"></div>
                  <!-- 详细数值 -->
                  <div class="confidence-details">
                    <div class="confidence-value">
                      <span class="value confidence-percentage">{{ currentTask.ai_result.confidence }}%</span>
                      <span class="label">整体置信度</span>
                    </div>
                    <div class="confidence-level" :class="getConfidenceLevel(currentTask.ai_result.confidence)">
                      {{ getConfidenceLevelText(currentTask.ai_result.confidence) }}
                    </div>
                  </div>
                </div>
              </el-descriptions-item>

              <el-descriptions-item label="AI分析">
                <div class="analysis-text">
                  {{ currentTask.ai_result.analysis_details }}
                </div>
              </el-descriptions-item>

              <el-descriptions-item label="模型版本">
                <el-tag type="info">{{ currentTask.ai_result.model_version }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="result-actions">
              <el-button type="success" @click="viewDetail">
                <el-icon><View /></el-icon>
                查看详情
              </el-button>
            </div>
          </div>

          <!-- 分析失败状态 -->
          <div v-else class="failed-result">
            <el-result
              icon="error"
              title="分析失败"
              :sub-title="'任务ID: ' + currentTask.task_info.task_id"
            >
              <template #extra>
                <el-button type="primary" @click="resetForm">
                  重新提交
                </el-button>
              </template>
            </el-result>
          </div>
          </el-card>
        </section>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm, ElMessageBox } from 'element-plus'
import {
  Upload,
  UploadFilled,
  Document,
  DataAnalysis,
  Delete,
  Loading,
  View,
  CircleCheckFilled,
  WarningFilled,
  CircleCloseFilled,
  InfoFilled,
  Check,
  Clock,
  Timer
} from '@element-plus/icons-vue'
import { submitTask } from '@/api/scoring'
import ScoringSkeleton from '@/components/LoadingStates/ScoringSkeleton.vue'
import * as echarts from 'echarts'

const store = useStore()
const router = useRouter()

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>()
const uploadRef = ref()

// 图表引用
const chartRef = ref<HTMLElement>()
let confidenceChart: echarts.ECharts | null = null

// 状态
const submitting = ref(false)
const imagePreview = ref('')
const pollingTimer = ref<NodeJS.Timeout | null>(null)

// AI分析进度状态
const analysisProgress = reactive({
  show: false,
  percentage: 0,
  status: 'success' as 'success' | 'exception' | 'warning',
  currentStep: '',
  estimatedTime: '',
  steps: [
    { text: '上传图像文件', completed: false, current: false, time: '' },
    { text: '图像预处理', completed: false, current: false, time: '' },
    { text: 'AI模型推理', completed: false, current: false, time: '' },
    { text: '结果分析', completed: false, current: false, time: '' },
    { text: '生成报告', completed: false, current: false, time: '' }
  ]
})

// 存储所有setTimeout定时器，用于组件卸载时清理
const activeTimeouts = ref<Set<NodeJS.Timeout>>(new Set())

// 安全的setTimeout包装器，自动追踪定时器
const safeSetTimeout = (callback: () => void, delay: number): NodeJS.Timeout => {
  const timer = setTimeout(() => {
    callback()
    // 从活跃定时器集合中移除
    activeTimeouts.value.delete(timer)
  }, delay)

  // 添加到活跃定时器集合
  activeTimeouts.value.add(timer)
  return timer
}

// 节流函数：优化高频事件性能
const createThrottle = <T extends (...args: any[]) => void>(func: T, delay: number): T => {
  let lastCall = 0
  let timeoutId: NodeJS.Timeout | null = null

  return ((...args: any[]) => {
    const now = Date.now()

    if (now - lastCall >= delay) {
      lastCall = now
      func(...args)
    } else if (!timeoutId) {
      // 在防抖期间设置一个定时器确保最终执行
      timeoutId = safeSetTimeout(() => {
        lastCall = Date.now()
        func(...args)
        timeoutId = null
      }, delay - (now - lastCall))
    }
  }) as T
}

// 图表响应式处理 - 使用节流优化高频事件
const handleChartResize = createThrottle(() => {
  if (confidenceChart) {
    confidenceChart.resize()
  }
}, 150) // 每150ms最多执行一次，优化性能

// 全屏拖放状态
const isDragOver = ref(false)

// 模型状态
const modelStatus = ref({
  status: 'checking', // 'checking', 'available', 'unavailable'
  message: '',
  lastCheck: null as Date | null
})

// 表单数据
const form = reactive({
  image: null as File | null,
  patient_code: '',
  clinical_text: ''
})

// 表单验证规则
const formRules = {
  image: [
    { required: true, message: '请上传内镜图像', trigger: 'change' }
  ],
  patient_code: [
    { min: 0, max: 50, message: '患者编号长度不能超过 50 个字符', trigger: 'blur' }
  ]
}

// 严重程度等级定义
const severityLevels = [
  { name: '缓解期', value: 1, color: '#67c23a' },
  { name: '轻度', value: 2, color: '#e6a23c' },
  { name: '中度', value: 3, color: '#f56c6c' },
  { name: '重度', value: 4, color: '#ff4444' }
]

// 计算属性
const currentTask = computed(() => store.state.scoring.currentTask)

// 检查真实AI模型状态
const checkModelStatus = async () => {
  modelStatus.value.status = 'checking'

  try {
    // 检查后端API健康状态
    const backendResponse = await fetch('/api/health')
    if (!backendResponse.ok) {
      throw new Error('后端服务不可用')
    }

    const backendData = await backendResponse.json()

    // 检查AI模型服务健康状态
    const aiModelResponse = await fetch('/api/ai/health')
    if (!aiModelResponse.ok) {
      throw new Error('真实AI模型服务不可用')
    }

    const aiModelData = await aiModelResponse.json()

    // 验证是否是真实模型 - 修正检测逻辑
    if (aiModelData.model_loaded && aiModelData.status === 'healthy') {
      modelStatus.value = {
        status: 'available',
        message: `真实AI模型运行正常 (${aiModelData.device || 'CPU'})`,
        lastCheck: new Date()
      }
    } else {
      throw new Error('检测到模拟模型，未使用真实AI模型')
    }

  } catch (error) {
    modelStatus.value = {
      status: 'unavailable',
      message: error.message || '真实AI模型服务不可用，请检查模型服务是否启动',
      lastCheck: new Date()
    }
  }
}

// 定期检查模型状态
let statusCheckTimer: NodeJS.Timeout | null = null

// 处理文件变化
const handleFileChange = (file: any) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/dcm', 'image/bmp']
  const maxSize = 10 * 1024 * 1024 // 10MB

  if (!validTypes.includes(file.raw.type)) {
    ElMessage.error('文件格式不正确，请上传 JPG、PNG、DICOM 或 BMP 格式的文件')
    return false
  }

  if (file.raw.size > maxSize) {
    ElMessage.error('文件大小不能超过 10MB')
    return false
  }

  form.image = file.raw

  // 创建预览（如果是图像文件）
  if (file.raw.type.startsWith('image/')) {
    const reader = new FileReader()
    reader.onload = (e) => {
      imagePreview.value = e.target?.result as string
      // 文件上传成功后触发动画
      onFileUploaded()
    }
    reader.readAsDataURL(file.raw)
  }

  return true
}

// 处理文件删除
const handleFileRemove = () => {
  form.image = null
  imagePreview.value = ''
}

// 处理全局拖放文件
const handleGlobalDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false

  const files = event.dataTransfer?.files
  if (!files || files.length === 0) return

  // 只处理第一个文件
  const file = files[0]
  handleFileFromGlobal(file)
}

// 处理从全局拖放或粘贴的文件
const handleFileFromGlobal = (file: File) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/dcm', 'image/bmp']
  const maxSize = 10 * 1024 * 1024 // 10MB

  if (!validTypes.includes(file.type)) {
    ElMessage({
      type: 'warning',
      message: '文件格式不正确，请上传 JPG、PNG、DICOM 或 BMP 格式的文件',
      offset: 80
    })
    return false
  }

  if (file.size > maxSize) {
    ElMessage({
      type: 'warning',
      message: '文件大小不能超过 10MB',
      offset: 80
    })
    return false
  }

  // 模拟文件上传组件的change事件
  const mockChangeEvent = {
    name: file.name,
    raw: file,
    status: 'ready',
    percentage: 0
  }

  handleFileChange(mockChangeEvent)
  return true
}

// 处理Ctrl+V粘贴
const handlePaste = (event: ClipboardEvent) => {
  const items = event.clipboardData?.items
  if (!items) return

  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.type.indexOf('image') !== -1) {
      event.preventDefault()
      const file = item.getAsFile()
      if (file) {
        handleFileFromGlobal(file)
        ElMessage({
          type: 'success',
          message: '图片已通过粘贴添加',
          offset: 80
        })
      }
      break
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      onValidationFailed()
      return
    }

    submitting.value = true

    // 初始化AI分析进度
    initializeAnalysisProgress()

    // TDP-004: 立即清空旧结果，防止数据显示混乱
    store.dispatch('scoring/clearCurrentTask')

    // 创建FormData
    const formData = new FormData()
    formData.append('image', form.image!)  // 修改字段名为 'image' 以匹配后端期望
    
    // 确保patient_code不为空，如果为空则生成默认值
    const patientCode = form.patient_code.trim() || `AUTO_${Date.now()}`
    formData.append('patient_code', patientCode)
    
    if (form.clinical_text.trim()) {
      formData.append('clinical_text', form.clinical_text.trim())
    }

    // 提交任务
    const response = await submitTask(formData)

    if (response.success) {
      ElMessage.success('任务提交成功，正在进行AI分析...')

      // 触发成功动画
      onSubmitSuccess()

      // TDP-003: 提交成功，重置表单以允许连续上传
      if (formRef.value) {
        formRef.value.resetFields()
      }
      form.image = null
      form.patient_code = ''
      form.clinical_text = ''
      imagePreview.value = ''

      // 关键：清空 el-upload 的文件列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }

      // 获取任务详情并开始轮询
      await startPolling(response.data.task_id)
    } else {
      ElMessage.error(response.message || '提交失败')
    }
  } catch (error) {
    console.error('Submit error:', error)

    // 检查是否是真实模型不可用错误
    if (error.response?.data?.error === 'MODEL_NOT_AVAILABLE') {
      ElMessage({
        type: 'error',
        message: '真实AI模型未启动',
        description: '请启动真实AI模型服务后重试',
        duration: 0,
        showClose: true
      })

      // 显示模型未启动提示
      ElMessageBox.alert(
        '真实AI模型服务未启动或不可用\n\n请确保：\n1. 真实AI模型服务正在运行 (端口5001)\n2. 模型文件路径正确\n3. GPU资源可用\n\n如需帮助，请联系系统管理员',
        '⚠️ 真实AI模型不可用',
        {
          confirmButtonText: '了解',
          type: 'warning',
          center: true
        }
      )
    } else if (error.response?.data?.error === 'AI_SERVICE_ERROR') {
      ElMessage.error('AI分析服务出错: ' + (error.response.data.message || '未知错误'))
    } else {
      ElMessage.error('提交失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

// 开始轮询任务状态
const startPolling = async (taskId: number) => {
  // 清除之前的轮询
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }

  // 立即获取一次结果
  await store.dispatch('scoring/getTaskResult', taskId)

  // 开始轮询，将轮询间隔从3秒增加到5秒，减少服务器压力
  pollingTimer.value = setInterval(async () => {
    await store.dispatch('scoring/getTaskResult', taskId)

    const task = store.state.scoring.currentTask
    if (task && (task.task_info.status === 3 || task.task_info.status === 4)) {
      // 任务完成或失败，停止轮询
      if (pollingTimer.value) {
        clearInterval(pollingTimer.value)
        pollingTimer.value = null
      }

      if (task.task_info.status === 3) {
        ElMessage.success('AI分析完成！')
        completeAnalysisProgress()
      } else {
        ElMessage.error('AI分析失败，请稍后重试')
        resetAnalysisProgress()
      }
      submitting.value = false
    }
  }, 5000) // 从3秒增加到5秒轮询一次，减少服务器压力
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.image = null
  form.patient_code = ''
  form.clinical_text = ''
  imagePreview.value = ''

  // 重置AI分析进度
  resetAnalysisProgress()

  // TDP-003: 确保清空 el-upload 的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }

  // 停止轮询
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }

  // 清空当前任务
  store.dispatch('scoring/clearCurrentTask')
}

// 查看详情
const viewDetail = () => {
  if (currentTask.value) {
    router.push(`/scoring/detail/${currentTask.value.task_id}`)
  }
}

// 获取严重程度标签类型
const getSeverityTagType = (severity: number) => {
  const typeMap = {
    1: 'success', // 缓解期
    2: '',        // 轻度
    3: 'warning', // 中度
    4: 'danger'   // 重度
  }
  return typeMap[severity] || 'info'
}

// 获取严重程度CSS类
const getSeverityClass = (severity: number) => {
  const classMap = {
    1: 'severity-remission', // 缓解期
    2: 'severity-mild',       // 轻度
    3: 'severity-moderate',   // 中度
    4: 'severity-severe'      // 重度
  }
  return classMap[severity] || 'severity-unknown'
}

// 获取严重程度图标
const getSeverityIcon = (severity: number) => {
  const iconMap = {
    1: CircleCheckFilled, // 缓解期 - 绿色勾
    2: InfoFilled,        // 轻度 - 蓝色信息
    3: WarningFilled,     // 中度 - 橙色警告
    4: CircleCloseFilled  // 重度 - 红色X
  }
  return iconMap[severity] || InfoFilled
}

// 获取严重程度描述
const getSeverityDescription = (severity: number) => {
  const descMap = {
    1: '症状缓解，病情稳定',
    2: '轻度炎症，定期复查',
    3: '中度活动，需要治疗',
    4: '重度炎症，立即干预'
  }
  return descMap[severity] || '未知严重程度'
}

// 获取置信度颜色
const getConfidenceColor = (confidence: number) => {
  if (confidence >= 90) return '#67C23A'
  if (confidence >= 80) return '#E6A23C'
  return '#F56C6C'
}

// 获取置信度等级
const getConfidenceLevel = (confidence: number) => {
  if (confidence >= 90) return 'high'
  if (confidence >= 80) return 'medium'
  return 'low'
}

// 获取置信度等级文本
const getConfidenceLevelText = (confidence: number) => {
  if (confidence >= 90) return '高置信度'
  if (confidence >= 80) return '中等置信度'
  return '低置信度'
}

// 渲染置信度图表
const renderConfidenceChart = (confidence: number) => {
  if (!chartRef.value) return

  // 销毁之前的图表
  if (confidenceChart) {
    confidenceChart.dispose()
  }

  // 创建新的图表
  confidenceChart = echarts.init(chartRef.value)

  // 模拟AI模型对不同严重程度的置信度分布
  const severity = currentTask.value?.ai_result?.severity || 2
  let confidenceData = []

  // 根据AI预测结果生成置信度分布
  switch (severity) {
    case 1: // 缓解期
      confidenceData = [
        { name: '缓解期', value: confidence, itemStyle: { color: '#67c23a' } },
        { name: '轻度', value: Math.max(10, 100 - confidence - 5), itemStyle: { color: '#e6a23c' } },
        { name: '中度', value: Math.max(5, 100 - confidence - 15), itemStyle: { color: '#f56c6c' } },
        { name: '重度', value: Math.max(3, 100 - confidence - 20), itemStyle: { color: '#ff4444' } }
      ]
      break
    case 2: // 轻度
      confidenceData = [
        { name: '缓解期', value: Math.max(8, 100 - confidence - 10), itemStyle: { color: '#67c23a' } },
        { name: '轻度', value: confidence, itemStyle: { color: '#e6a23c' } },
        { name: '中度', value: Math.max(10, 100 - confidence - 8), itemStyle: { color: '#f56c6c' } },
        { name: '重度', value: Math.max(5, 100 - confidence - 15), itemStyle: { color: '#ff4444' } }
      ]
      break
    case 3: // 中度
      confidenceData = [
        { name: '缓解期', value: Math.max(3, 100 - confidence - 20), itemStyle: { color: '#67c23a' } },
        { name: '轻度', value: Math.max(10, 100 - confidence - 12), itemStyle: { color: '#e6a23c' } },
        { name: '中度', value: confidence, itemStyle: { color: '#f56c6c' } },
        { name: '重度', value: Math.max(8, 100 - confidence - 10), itemStyle: { color: '#ff4444' } }
      ]
      break
    case 4: // 重度
      confidenceData = [
        { name: '缓解期', value: Math.max(2, 100 - confidence - 25), itemStyle: { color: '#67c23a' } },
        { name: '轻度', value: Math.max(5, 100 - confidence - 20), itemStyle: { color: '#e6a23c' } },
        { name: '中度', value: Math.max(10, 100 - confidence - 15), itemStyle: { color: '#f56c6c' } },
        { name: '重度', value: confidence, itemStyle: { color: '#ff4444' } }
      ]
      break
    default:
      confidenceData = [
        { name: '轻度', value: confidence, itemStyle: { color: '#e6a23c' } },
        { name: '中度', value: Math.max(10, 100 - confidence), itemStyle: { color: '#f56c6c' } }
      ]
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e0e0',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12,
        color: '#666'
      }
    },
    series: [
      {
        name: 'AI置信度分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: confidenceData
      }
    ],
    animationType: 'scale',
    animationEasing: 'elasticOut',
    animationDelay: function (idx: number) {
      return Math.random() * 200
    }
  }

  confidenceChart.setOption(option)

  // 响应式处理
  window.addEventListener('resize', handleChartResize)
}

// ===== 微交互动画函数 =====
// 按钮悬停效果
const onButtonHover = (event: MouseEvent) => {
  const button = event.currentTarget as HTMLElement
  if (button && !submitting.value) {
    // 添加微妙的发光效果
    button.style.boxShadow = '0 0 0 2px var(--aperture-primary-light), var(--aperture-shadow-medium)'
  }
}

// 按钮离开效果
const onButtonLeave = (event: MouseEvent) => {
  const button = event.currentTarget as HTMLElement
  if (button && !submitting.value) {
    button.style.boxShadow = 'var(--aperture-shadow-light)'
  }
}

// 文件上传成功动画
const onFileUploaded = () => {
  // 为上传成功的文件添加弹跳动画
  safeSetTimeout(() => {
    const uploadedFile = document.querySelector('.uploaded-file')
    if (uploadedFile) {
      uploadedFile.classList.add('aperture-bounce')
      safeSetTimeout(() => {
        uploadedFile.classList.remove('aperture-bounce')
      }, 500)
    }
  }, 100)
}

// 表单验证失败震动效果
const onValidationFailed = () => {
  const form = document.querySelector('.scoring-form')
  if (form) {
    form.classList.add('aperture-shake')
    safeSetTimeout(() => {
      form.classList.remove('aperture-shake')
    }, 350)
  }
}

// 任务提交成功庆祝动画
const onSubmitSuccess = () => {
  // 创建成功提示的动画效果
  const cards = document.querySelectorAll('.upload-card, .result-card')
  cards.forEach((card, index) => {
    safeSetTimeout(() => {
      card.classList.add('aperture-glow')
      safeSetTimeout(() => {
        card.classList.remove('aperture-glow')
      }, 2000)
    }, index * 100)
  })
}

// 组件挂载时初始化
onMounted(() => {
  // 立即检查一次模型状态
  checkModelStatus()

  // 每30秒定期检查模型状态
  statusCheckTimer = setInterval(() => {
    checkModelStatus()
  }, 30000)

  // 添加全局拖放事件监听器
  document.addEventListener('dragover', handleGlobalDragOver)
  document.addEventListener('drop', handleGlobalDrop)
  document.addEventListener('paste', handlePaste)

  // 显示AI模型状态Toast通知
  safeSetTimeout(() => {
    if (modelStatus.value.status === 'available') {
      ElMessage({
        type: 'success',
        message: '✅ AI模型已就绪，可开始分析',
        offset: 80,
        duration: 3000
      })
    }
  }, 2000)
})

// 全局拖拽悬停处理
const handleGlobalDragOver = (event: DragEvent) => {
  event.preventDefault()

  // 检查是否有文件被拖拽
  const hasFiles = event.dataTransfer?.types.includes('Files')
  if (hasFiles && !isDragOver.value) {
    isDragOver.value = true
  }
}

// 监听AI结果变化，自动渲染图表
watch(currentTask, (newTask) => {
  if (newTask?.ai_result?.confidence !== undefined) {
    // 等待DOM更新后再渲染图表
    nextTick(() => {
      renderConfidenceChart(newTask.ai_result.confidence)
    })
  }
}, { deep: true })

// 组件卸载时清理
onUnmounted(() => {
  // 清理轮询定时器
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }

  // 清理状态检查定时器
  if (statusCheckTimer) {
    clearInterval(statusCheckTimer)
    statusCheckTimer = null
  }

  // 清理所有活跃的setTimeout定时器 - 防止内存泄漏
  activeTimeouts.value.forEach(timerId => {
    clearTimeout(timerId)
  })
  activeTimeouts.value.clear()

  // 移除全局事件监听器
  document.removeEventListener('dragover', handleGlobalDragOver)
  document.removeEventListener('drop', handleGlobalDrop)
  document.removeEventListener('paste', handlePaste)

  // 清理图表
  if (confidenceChart) {
    confidenceChart.dispose()
  }
  window.removeEventListener('resize', handleChartResize)
})

// AI分析进度管理函数
const initializeAnalysisProgress = () => {
  analysisProgress.show = true
  analysisProgress.percentage = 0
  analysisProgress.status = 'success'
  analysisProgress.currentStep = '准备上传图像...'
  analysisProgress.estimatedTime = '预计 10-15 秒'
  
  // 重置所有步骤
  analysisProgress.steps.forEach((step, index) => {
    step.completed = false
    step.current = index === 0
    step.time = ''
  })

  // 开始模拟进度
  simulateAnalysisProgress()
}

const simulateAnalysisProgress = () => {
  const progressSteps = [
    { percentage: 20, step: 0, message: '上传图像文件...', duration: 2000 },
    { percentage: 40, step: 1, message: '图像预处理中...', duration: 3000 },
    { percentage: 60, step: 2, message: 'AI模型推理中...', duration: 4000 },
    { percentage: 80, step: 3, message: '结果分析中...', duration: 2000 },
    { percentage: 95, step: 4, message: '生成分析报告...', duration: 1000 }
  ]

  let currentStepIndex = 0

  const executeNextStep = () => {
    if (currentStepIndex >= progressSteps.length) {
      // 进度完成，等待实际结果
      analysisProgress.currentStep = '等待AI服务返回结果...'
      analysisProgress.estimatedTime = '即将完成'
      return
    }

    const step = progressSteps[currentStepIndex]
    
    // 更新进度条
    analysisProgress.percentage = step.percentage
    analysisProgress.currentStep = step.message
    
    // 更新步骤状态
    analysisProgress.steps.forEach((s, index) => {
      if (index < step) {
        s.completed = true
        s.current = false
        s.time = '✓'
      } else if (index === step) {
        s.current = true
        s.time = '...'
      } else {
        s.completed = false
        s.current = false
        s.time = ''
      }
    })

    // 更新预计时间
    const remainingSteps = progressSteps.length - currentStepIndex - 1
    const estimatedSeconds = remainingSteps * 2 + 3
    analysisProgress.estimatedTime = `预计 ${estimatedSeconds} 秒`

    currentStepIndex++
    safeSetTimeout(executeNextStep, step.duration)
  }

  // 开始执行第一步
  executeNextStep()
}

const completeAnalysisProgress = () => {
  analysisProgress.percentage = 100
  analysisProgress.currentStep = 'AI分析完成！'
  analysisProgress.estimatedTime = ''
  
  // 标记所有步骤为完成
  analysisProgress.steps.forEach(step => {
    step.completed = true
    step.current = false
    step.time = '✓'
  })

  // 3秒后隐藏进度卡片
  safeSetTimeout(() => {
    analysisProgress.show = false
  }, 3000)
}

const resetAnalysisProgress = () => {
  analysisProgress.show = false
  analysisProgress.percentage = 0
  analysisProgress.currentStep = ''
  analysisProgress.estimatedTime = ''
  
  analysisProgress.steps.forEach(step => {
    step.completed = false
    step.current = false
    step.time = ''
  })
}
</script>

<style scoped>
/* ===== 智能驾驶舱 CSS Grid布局系统 ===== */
.new-scoring-page {
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
}

/* CSS Grid容器布局 */
.scoring-grid-container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: auto 1fr;
  gap: 0;
  min-height: 100vh;
  max-width: 1600px;
  margin: 0 auto;
  padding: 24px;
}

/* 顶部标题区域 */
.page-header {
  display: grid;
  grid-template-columns: 1fr auto;
  align-items: center;
  margin-bottom: 32px;
  padding: 16px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.4) 100%);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px 32px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0;
  background: linear-gradient(135deg, #2d3748 0%, #1a202c 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: -0.5px;
  animation: fadeInUp 0.6s ease-out;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 模型状态徽章 */
.model-status-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.model-status-badge.checking {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
  border-color: rgba(64, 158, 255, 0.2);
}

.model-status-badge.available {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border-color: rgba(103, 194, 58, 0.2);
}

.model-status-badge.unavailable {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  border-color: rgba(245, 108, 108, 0.2);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-dot.checking {
  background: #409eff;
}

.status-dot.available {
  background: #67c23a;
}

.status-dot.unavailable {
  background: #f56c6c;
}

/* 主要内容区域：CSS Grid布局 */
.scoring-main-grid {
  display: grid;
  grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
  gap: 32px;
  align-items: start;
  animation: fadeInUp 0.8s ease-out 0.2s both;
}

.upload-section,
.result-section {
  width: 100%;
  min-width: 0; /* 防止grid子项溢出 */
}

/* 全屏拖放遮罩 */
.fullscreen-drag-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 122, 255, 0.1);
  backdrop-filter: blur(8px);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: fadeIn 0.3s ease-out;
}

.drag-overlay-content {
  text-align: center;
  padding: 40px 60px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 24px;
  border: 3px dashed #007aff;
  box-shadow: 0 20px 60px rgba(0, 122, 255, 0.3);
  backdrop-filter: blur(20px);
  transform: scale(1);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.drag-overlay-content:hover {
  transform: scale(1.05);
}

.drag-overlay-icon {
  font-size: 64px;
  color: #007aff;
  margin-bottom: 16px;
  animation: bounce 2s infinite;
}

.drag-overlay-content h3 {
  font-size: 24px;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 8px 0;
}

.drag-overlay-content p {
  font-size: 16px;
  color: #4a5568;
  margin: 0;
}

/* 毛玻璃卡片效果 */
.glass-effect {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  -webkit-backdrop-filter: blur(20px) saturate(180%);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  box-shadow:
    0 20px 40px rgba(0, 0, 0, 0.06),
    0 0 0 1px rgba(255, 255, 255, 0.05) inset;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.glass-effect:hover {
  transform: translateY(-4px);
  box-shadow:
    0 30px 60px rgba(0, 0, 0, 0.12),
    0 0 0 1px rgba(255, 255, 255, 0.1) inset;
}

/* 卡片头部样式 */
.card-header {
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  font-weight: 600;
  font-size: 18px;
  padding: 20px 24px;
  background: linear-gradient(135deg,
    rgba(255, 255, 255, 0.9) 0%,
    rgba(255, 255, 255, 0.6) 100%);
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
}

.header-icon {
  color: #007aff;
  font-size: 20px;
  transition: all 0.3s ease;
}

.upload-card:hover .header-icon {
  transform: scale(1.1) rotate(5deg);
}

.ai-model-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  animation: pulse 2s infinite;
}

.result-status {
  display: flex;
  align-items: center;
}

.loading-icon {
  color: #007aff;
  animation: spin 2s linear infinite;
}

/* 表单样式 */
.scoring-form {
  padding: 32px 24px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #2d3748;
  font-size: 16px;
}

/* 智能上传区域 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 220px;
  border: 2px dashed rgba(0, 122, 255, 0.3);
  border-radius: 16px;
  background: linear-gradient(135deg,
    rgba(240, 248, 255, 0.8) 0%,
    rgba(226, 240, 255, 0.8) 100%);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

:deep(.el-upload-dragger:hover) {
  border-color: #007aff;
  background: linear-gradient(135deg,
    rgba(226, 240, 255, 0.9) 0%,
    rgba(186, 230, 253, 0.9) 100%);
  transform: scale(1.02);
  box-shadow: 0 0 0 4px rgba(0, 122, 255, 0.1);
}

:deep(.el-upload-dragger.is-dragover) {
  border-color: #007aff;
  background: linear-gradient(135deg,
    rgba(186, 230, 253, 0.9) 0%,
    rgba(147, 197, 253, 0.9) 100%);
  box-shadow: 0 0 0 6px rgba(0, 122, 255, 0.2);
  transform: scale(1.03);
}

.upload-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 32px;
}

.upload-icon {
  font-size: 64px;
  color: rgba(0, 122, 255, 0.6);
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

:deep(.el-upload-dragger:hover) .upload-icon {
  color: #007aff;
  transform: scale(1.1);
}

.upload-text {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 14px;
  color: #718096;
  line-height: 1.5;
}

/* 上传文件展示 */
.uploaded-file {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg,
    rgba(240, 248, 255, 0.8) 0%,
    rgba(226, 240, 255, 0.8) 100%);
  border-radius: 16px;
  border: 1px solid rgba(0, 122, 255, 0.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  animation: slideInUp 0.4s ease-out;
}

.preview-image {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  margin-right: 16px;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.preview-image:hover {
  transform: scale(1.05);
}

.file-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-name {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  word-break: break-all;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper:hover) {
  border-color: rgba(0, 122, 255, 0.3);
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.05);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1), 0 0 20px rgba(0, 122, 255, 0.15);
}

:deep(.el-textarea__inner) {
  border-radius: 12px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.1);
  resize: vertical;
}

:deep(.el-textarea__inner:hover) {
  border-color: rgba(0, 122, 255, 0.3);
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.05);
}

:deep(.el-textarea__inner:focus) {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1), 0 0 20px rgba(0, 122, 255, 0.15);
}

/* 提交按钮 */
.submit-section {
  margin-top: 32px;
  text-align: center;
}

.submit-button {
  width: 100%;
  max-width: 320px;
  height: 56px;
  font-size: 18px;
  font-weight: 700;
  border-radius: 16px;
  background: linear-gradient(135deg, #007aff 0%, #5856d6 100%);
  border: none;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  letter-spacing: 0.5px;
}

.submit-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg,
    transparent 0%,
    rgba(255, 255, 255, 0.3) 50%,
    transparent 100%);
  transition: left 0.6s ease;
}

.submit-button:hover::before {
  left: 100%;
}

.submit-button:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 20px 40px rgba(0, 122, 255, 0.3);
}

.submit-button:active {
  transform: translateY(-1px) scale(0.98);
}

/* 结果展示区域 */
.empty-result,
.analyzing-result,
.completed-result,
.failed-result {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px 24px;
}

.empty-icon {
  font-size: 80px;
  color: rgba(0, 0, 0, 0.2);
}

/* 完成结果样式 */
.completed-result {
  flex-direction: column;
  align-items: stretch;
  width: 100%;
  animation: slideInUp 0.6s ease-out;
}

.result-descriptions {
  margin-bottom: 24px;
}

.score-tag,
.severity-tag {
  font-size: 18px;
  font-weight: 700;
  padding: 8px 16px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 严重程度药丸标签样式 */
.severity-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.severity-pill {
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border-radius: 16px;
  border: none;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: severityPulse 2s ease-in-out infinite alternate;
}

.severity-pill::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent 0%, rgba(255, 255, 255, 0.1) 50%, transparent 100%);
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}

.severity-pill:hover::before {
  transform: translateX(100%);
}

.severity-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  font-size: 24px;
  transition: all 0.3s ease;
}

.severity-pill:hover .severity-icon {
  transform: scale(1.1) rotate(5deg);
  background: rgba(255, 255, 255, 0.3);
}

.severity-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.severity-title {
  font-size: 20px;
  font-weight: 700;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.severity-subtitle {
  font-size: 14px;
  opacity: 0.9;
  color: rgba(255, 255, 255, 0.95);
  font-weight: 500;
}

.severity-score {
  font-size: 24px;
  font-weight: 800;
  color: white;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 严重程度等级指示器 */
.severity-indicators {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.indicator {
  width: 40px;
  height: 6px;
  border-radius: 3px;
  background: rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.indicator::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.3) 50%, rgba(255, 255, 255, 0) 100%);
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}

.indicator.active::before {
  transform: translateX(100%);
}

/* 缓解期样式 */
.severity-remission {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  box-shadow: 0 8px 25px rgba(103, 194, 58, 0.3);
}

.severity-remission .indicator:nth-child(1) {
  background: #67c23a;
  box-shadow: 0 0 12px rgba(103, 194, 58, 0.5);
}

/* 轻度样式 */
.severity-mild {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.3);
}

.severity-mild .indicator:nth-child(1),
.severity-mild .indicator:nth-child(2) {
  background: #409eff;
  box-shadow: 0 0 12px rgba(64, 158, 255, 0.5);
}

/* 中度样式 */
.severity-moderate {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
  box-shadow: 0 8px 25px rgba(230, 162, 60, 0.3);
}

.severity-moderate .indicator:nth-child(1),
.severity-moderate .indicator:nth-child(2),
.severity-moderate .indicator:nth-child(3) {
  background: #e6a23c;
  box-shadow: 0 0 12px rgba(230, 162, 60, 0.5);
}

/* 重度样式 */
.severity-severe {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  box-shadow: 0 8px 25px rgba(245, 108, 108, 0.3);
}

.severity-severe .indicator:nth-child(1),
.severity-severe .indicator:nth-child(2),
.severity-severe .indicator:nth-child(3),
.severity-severe .indicator:nth-child(4) {
  background: #f56c6c;
  box-shadow: 0 0 12px rgba(245, 108, 108, 0.5);
}

@keyframes severityPulse {
  0% {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
  }
  100% {
    box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
  }
}

.confidence-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.confidence-progress {
  flex: 1;
}

.confidence-text {
  font-size: 16px;
  font-weight: 700;
  color: #2d3748;
  min-width: 60px;
  text-align: right;
}

/* 置信度可视化样式 */
.confidence-visualization {
  display: grid;
  grid-template-columns: 1fr auto;
  gap: 24px;
  align-items: center;
}

.confidence-chart {
  height: 200px;
  width: 100%;
  min-height: 200px;
}

.confidence-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 8px;
}

.confidence-value {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.confidence-value .value {
  font-size: 32px;
  font-weight: 800;
  line-height: 1;
  background: linear-gradient(135deg, #007aff 0%, #5856d6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.confidence-value .label {
  font-size: 12px;
  color: #718096;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.confidence-level {
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.confidence-level.high {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
}

.confidence-level.medium {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
  color: white;
}

.confidence-level.low {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  color: white;
}

.analysis-text {
  font-size: 14px;
  color: #4a5568;
  line-height: 1.6;
  background: linear-gradient(135deg,
    rgba(240, 248, 255, 0.8) 0%,
    rgba(226, 240, 255, 0.8) 100%);
  padding: 16px;
  border-radius: 12px;
  border-left: 4px solid #007aff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.result-actions {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@keyframes bounce {
  0%, 20%, 53%, 80%, 100% { transform: translateY(0); }
  40%, 43% { transform: translateY(-10px); }
  70% { transform: translateY(-5px); }
  90% { transform: translateY(-2px); }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .scoring-main-grid {
    grid-template-columns: 1fr;
    gap: 24px;
  }

  .upload-section,
  .result-section {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .scoring-grid-container {
    padding: 16px;
  }

  .page-header {
    grid-template-columns: 1fr;
    text-align: center;
    gap: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .scoring-form {
    padding: 24px 16px;
  }

  :deep(.el-upload-dragger) {
    height: 180px;
  }

  .upload-icon {
    font-size: 48px;
  }

  .submit-button {
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .card-header {
    grid-template-columns: auto 1fr;
    gap: 8px;
  }

  .ai-model-indicator {
    grid-column: 1 / -1;
    justify-self: start;
  }

  .confidence-container {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .confidence-text {
    text-align: center;
  }

  .confidence-visualization {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .confidence-chart {
    height: 180px;
  }

  .confidence-details {
    order: -1;
    margin-bottom: 8px;
  }

  .severity-pill {
    grid-template-columns: auto 1fr;
    gap: 12px;
    padding: 16px;
  }

  .severity-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }

  .severity-title {
    font-size: 18px;
  }

  .severity-score {
    grid-column: 1 / -1;
    justify-self: center;
    font-size: 20px;
  }

  .severity-indicators {
    margin-top: 8px;
  }

  .indicator {
    width: 32px;
  }
}

/* AI分析进度样式 */
.analysis-progress-card {
  margin-top: 24px;
  animation: slideInUp 0.5s ease-out;
}

.progress-card {
  border: 1px solid var(--el-border-color-light);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
}

.progress-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.progress-icon {
  color: var(--el-color-primary);
  animation: spin 2s linear infinite;
}

.progress-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-bar-container {
  margin: 8px 0;
}

.progress-text {
  font-weight: 600;
  color: var(--el-color-primary);
}

.current-step {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: var(--el-color-primary-light-9);
  border-radius: 8px;
  border-left: 4px solid var(--el-color-primary);
  color: var(--el-color-primary);
  font-weight: 500;
}

.step-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.step-item.completed {
  background: var(--el-color-success-light-9);
  color: var(--el-color-success);
}

.step-item.current {
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  font-weight: 500;
}

.step-item.pending {
  background: var(--el-fill-color-lighter);
  color: var(--el-text-color-regular);
}

.step-icon {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.step-text {
  flex: 1;
}

.step-time {
  font-size: 12px;
  font-weight: 600;
}

.estimated-time {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: var(--el-fill-color-light);
  border-radius: 6px;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>